import React, { useState, useEffect } from 'react';
import { 
  TableCellsIcon, 
  CalendarIcon, 
  CurrencyYenIcon,
  IdentificationIcon,
  ExclamationCircleIcon
} from '@heroicons/react/24/outline';
import Card from '../components/Card';
import { getDashboardData, getUnpaidBills } from '../services/api';
import { Link } from 'react-router-dom';

const Dashboard = () => {
  const [dashboardData, setDashboardData] = useState({
    parking_summary: { free_spots: 0, occupied_spots: 0, total_spots: 0 },
    reservation_count: 0,
    total_income: 0,
    recent_records: [],
    recent_detections: []
  });
  const [unpaidBills, setUnpaidBills] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 首次加载数据
    const fetchData = async () => {
      try {
        if (loading) {
          setLoading(true);
        }
        const [dashboardResponse, unpaidResponse] = await Promise.all([
          getDashboardData(),
          getUnpaidBills()
        ]);
        
        setDashboardData(dashboardResponse.data);
        setUnpaidBills(unpaidResponse.data);
        setError(null);
      } catch (err) {
        console.error('获取仪表盘数据失败:', err);
        setError('获取数据失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
    
    // 设置重要数据的定时刷新
    const importantDataIntervalId = setInterval(async () => {
      try {
        // 获取重要数据(车位摘要和未支付账单)，不设置loading状态
        const [dashboardResponse, unpaidResponse] = await Promise.all([
          getDashboardData(),
          getUnpaidBills()
        ]);
        
        // 只更新重要数据部分
        setDashboardData(prev => ({
          ...prev,
          parking_summary: dashboardResponse.data.parking_summary,
          reservation_count: dashboardResponse.data.reservation_count,
          total_income: dashboardResponse.data.total_income
        }));
        setUnpaidBills(unpaidResponse.data);
      } catch (err) {
        console.error('更新重要仪表盘数据失败:', err);
      }
    }, 1000); // 每1秒刷新重要数据
    
    // 设置不重要数据的定时刷新
    const lessImportantDataIntervalId = setInterval(async () => {
      try {
        // 获取不太重要的数据(最近记录)
        const dashboardResponse = await getDashboardData();
        
        // 只更新不重要数据部分
        setDashboardData(prev => ({
          ...prev,
          recent_records: dashboardResponse.data.recent_records,
          recent_detections: dashboardResponse.data.recent_detections
        }));
      } catch (err) {
        console.error('更新次要仪表盘数据失败:', err);
      }
    }, 5000); // 每5秒刷新不重要数据
    
    return () => {
      clearInterval(importantDataIntervalId);
      clearInterval(lessImportantDataIntervalId);
    };
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  const { parking_summary, reservation_count, total_income, recent_records, recent_detections } = dashboardData;

  // 计算未支付账单总金额
  const unpaidTotal = unpaidBills.reduce((sum, bill) => sum + bill.amount, 0);

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-gray-800">仪表盘</h1>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card 
          title="空闲车位" 
          value={parking_summary.free_spots} 
          icon={TableCellsIcon} 
          color="green" 
        />
        <Card 
          title="占用车位" 
          value={parking_summary.occupied_spots} 
          icon={TableCellsIcon} 
          color="red" 
        />
        <Card 
          title="待处理预约" 
          value={reservation_count} 
          icon={CalendarIcon} 
          color="blue" 
        />
        <Card 
          title="总收入 (元)" 
          value={total_income.toFixed(2)} 
          icon={CurrencyYenIcon} 
          color="yellow" 
        />
      </div>
      
      {/* 未支付账单提醒 */}
      {unpaidBills.length > 0 && (
        <div className="bg-red-50 border-l-4 border-red-500 p-4 rounded-md shadow-md">
          <div className="flex items-start">
            <div className="flex-shrink-0">
              <ExclamationCircleIcon className="h-6 w-6 text-red-500" />
            </div>
            <div className="ml-3">
              <h3 className="text-lg font-medium text-red-800">未支付账单提醒</h3>
              <div className="mt-2 text-red-700">
                <p>当前有 <span className="font-bold">{unpaidBills.length}</span> 笔账单未支付，总金额：<span className="font-bold">{unpaidTotal.toFixed(2)}</span> 元</p>
                <Link 
                  to="/income" 
                  className="mt-2 inline-block bg-red-600 hover:bg-red-700 text-white py-1 px-4 rounded text-sm focus:outline-none focus:ring-2 focus:ring-red-500"
                >
                  查看未支付账单
                </Link>
              </div>
            </div>
          </div>
        </div>
      )}
      
      {/* 最近车牌识别记录 */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4">最近车牌识别记录</h2>
        
        {recent_detections && recent_detections.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    车牌号
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    识别时间
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {recent_detections.map((detection) => (
                  <tr key={detection.id}>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {detection.plate_number}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {new Date(detection.detection_time).toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-gray-500">暂无车牌识别记录</p>
        )}
      </div>
      
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4">最近车辆记录</h2>
        
        {recent_records.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    车牌号
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    车位号
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    进入时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    离开时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    支付状态
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {recent_records.map((record) => {
                  // 检查该记录是否有对应的未支付账单
                  const hasUnpaidBill = record.status === 'exited' && 
                    unpaidBills.some(bill => bill.record_id === record.id);
                    
                  return (
                    <tr key={record.id} className={hasUnpaidBill ? 'bg-red-50' : ''}>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {record.plate_number}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {record.spot_number}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                          record.status === 'exited' 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-blue-100 text-blue-800'
                        }`}>
                          {record.status === 'exited' ? '已离开' : '已进入'}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {new Date(record.entry_time).toLocaleString()}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {record.exit_time ? new Date(record.exit_time).toLocaleString() : '-'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {record.status === 'exited' ? (
                          hasUnpaidBill ? (
                            <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">
                              未支付
                            </span>
                          ) : (
                            <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                              已支付
                            </span>
                          )
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-gray-500">暂无车辆记录</p>
        )}
      </div>
    </div>
  );
};

export default Dashboard; 